package ru.pb.dao.auth.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.log4j.Logger;

import ru.pb.auth.dao.ClanInfoDAO;
import ru.pb.global.dao.annotations.DAO;
import ru.pb.global.data.model.ClanInfo;
import ru.pb.global.data.model.ClanLogo;
import ru.pb.global.dbc.DatabaseFactory;
import ru.pb.global.dbc.DatabaseUtils;

/**
 * @author: Felixx
 */
@DAO(database = "MySQL")
public class ClanInfoDAOImpl implements ClanInfoDAO
{
	private static final Logger _log = Logger.getLogger(ClanInfoDAOImpl.class);

	@Override
	public ClanInfo getClanInfo(int clan_id, Connection con)
	{
		boolean needCloseConnection = con == null;

		PreparedStatement statement = null;
		ResultSet rset = null;
		ClanInfo clanInfo = new ClanInfo();
		try
		{
			if(needCloseConnection)
				con = DatabaseFactory.getInstance().newConnection();

			statement = con.prepareStatement("SELECT * FROM clan_data WHERE clan_id=? LIMIT 1");
			statement.setInt(1, clan_id);
			rset = statement.executeQuery();

			while(rset.next())
			{
				clanInfo.setClanRank(rset.getInt("clan_rank"));
				clanInfo.setClanName(rset.getString("clan_name"));
				clanInfo.setOwnerId(rset.getInt("owner_id"));

				byte logo1 = rset.getByte("logo1");
				byte logo2 = rset.getByte("logo2");
				byte logo3 = rset.getByte("logo3");
				byte logo4 = rset.getByte("logo4");
				byte color = rset.getByte("color");
				clanInfo.setClanLogo(new ClanLogo(logo1, logo2, logo3, logo4, color));

				return clanInfo;
			}
		}
		catch(final Exception e)
		{
			_log.info("Exception: " + e, e);
		}
		finally
		{
			if(needCloseConnection)
				DatabaseUtils.closeConnection(con);
			DatabaseUtils.closeDatabaseSR(statement, rset);
		}
		return clanInfo;
	}
}